import { Table } from 'antd';
import Item from 'antd/lib/list/Item';
import React, { useEffect, useState } from 'react';
import { Resizable } from 'react-resizable';
// import "../node_modules/react-resizable/css/styles.css";  // 引入react-resizable样式，否则无法显示Resize样式

// 重写Table组件header单元格渲染方式
const ResizableTitle = props => {
	const { onResize, width, ...restProps } = props;
	if (width === undefined) {
		return <th {...restProps}></th>;
	}
	return (
		// 外包一层Resizable组件
		// 其中onResize属性调用col.onResize方法
		<Resizable width={width} height={0} onResize={onResize}>
			<th {...restProps}></th>
		</Resizable>
	);
};

const ResizeTable = (props: { dataSource: any[]; columns: any[]; pagination: any; loading: boolean }) => {
	useEffect(() => {
		setColumns(
			props.columns.map(col => {
				// 注意：给每一列的onHeaderCell属性增加onResize方法，用于传递onResize事件
				col.onHeaderCell = () => ({
					width: col.width,
					onResize: handleResize(col)
				});
				return col;
			})
		);
	}, [props]);

	const [columns, setColumns] = useState<any[]>([]);
	// Table 组件 components
	const components = {
		header: {
			cell: ResizableTitle
		}
	};

	// 动态修改col.width属性
	const handleResize =
		column =>
		(e, { size }) => {
			console.log(column, e, size, columns);
			const cols = [...columns];
			cols.forEach(item => {
				if (item === column) {
					item.width = size.width;
				}
			});
			setColumns(cols);
		};

	return (
		<div style={{ width: '100%' }}>
			<Table scroll={{ y: window.innerHeight - 400 }} loading={props.loading} pagination={props.pagination} dataSource={props.dataSource} columns={columns} components={components} />
		</div>
	);
};

export default ResizeTable;
